//
//  XXGCD.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/30.
//

import Foundation

class XXGCD:NSObject{
    
    public typealias Task = ()-> Void
    
    // MARK: 异步执行
    public static func async( _ task:@escaping Task) {
       _async(task)
    }
    
    public static func async(_ task:@escaping Task, _ mainTask:@escaping Task){
        _async(task, mainTask)
    }
   
    private static func _async(_ task:@escaping Task, _ mainTask:Task? = nil){
        let item = DispatchWorkItem(block: task)
        DispatchQueue.global().async(execute: item)
        if let main = mainTask{
            item.notify(queue: DispatchQueue.main, execute: main)
        }
    }
    
    // MARK: 延迟
    public static func delay(_ time:Double, _ task:@escaping Task,  _ queue:XXQueueType = .main){
        let item = DispatchWorkItem(block: task)
        switch queue {
        case .main:
            DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: item)
        case .child:
            DispatchQueue.global().asyncAfter(deadline: .now() + time, execute: item)
        }
    }
    
    // MARK: 线程组
    enum XXQueueType{
        case main, child
    }
    var group:DispatchGroup?
    var queue:DispatchQueue?
    
    class func group() -> XXGCD{
        let gcd = XXGCD()
        gcd.group = DispatchGroup()
        gcd.queue = DispatchQueue(label: "groupQueue")
        return gcd
    }
    @discardableResult
    func async( _ block:@escaping XXVoidBlock) ->XXGCD {
        if let q = queue, let g = group{ // 组执行
            g.enter()
            q.async {
                block()
                g.leave()
            }
        }else{
            print("group、queue is nil")
        }
        return self
    }
    func done(_ block:@escaping XXVoidBlock){
        if let g = group{
            g.notify(queue: DispatchQueue.main) {
                block()
            }
        }else{
            print("group、queue is nil")
        }
    }
}
